package com.podcstr.controller;

import com.podcstr.entity.User;
import com.podcstr.qualifier.CurrentSession;
import com.podcstr.service.UserService;
import com.podcstr.service.exception.ServiceException;
import com.podcstr.session.UserSession;
import com.podcstr.utils.ActivationKeyGen;
import com.podcstr.utils.MD5CryptImpl;
import org.apache.log4j.Logger;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @author azim
 * @since 5/20/13 
 */

@Named
@RequestScoped
public class LoginController {

    private Logger logger = Logger.getLogger(LoginController.class.getName());
    private User user;
    FacesContext context;

    @Inject
    @CurrentSession
    private UserSession userSession;

    @EJB
    private UserService userService;

    @PostConstruct
    public void init() {

        context = FacesContext.getCurrentInstance();

        if (user == null) {
            user = new User();
        }
    }

    public String signUp() {

        if (user != null) {

            user.setActivationkey(ActivationKeyGen.generateKey(10));

            if (!user.getPassword().equals(user.getConfirmPassword())) {

                context.addMessage(null, new FacesMessage("Password and confirm password don't match."));
                return null;
            }

            try {

                user.setPassword(MD5CryptImpl.createPassPhrase(user.getPassword()));
                userService.signUp(user);
                context.addMessage(null, new FacesMessage("Registration Successful."));
            } catch (ServiceException e) {

                if (e.getViolations().size() != 0) {
                    context.addMessage(null, new FacesMessage(e.getViolations().toString()));
                }
                context.addMessage(null, new FacesMessage(e.getMessage()));
            }
        }

        return null;
    }

    public String login() {

        if (user != null) {

            user.setPassword(MD5CryptImpl.createPassPhrase(user.getPassword()));

            if (userService.verifyLogin(user.getUsername(), user.getPassword())) {
                ;

                user = userService.findUserByUsername(user.getUsername());
                userSession.setUser(user);
                logger.info(new Date() + " : " + user.getUsername() + " logged in.");

                return "index.xhtml?faces-redirect=true";
            } else {

                logger.debug(new Date() + " : Invalid username : " + user.getUsername() + " or password : " + user.getPassword());
                context.addMessage(null, new FacesMessage("Wrong Username or Password or Both"));
            }
        }

        return null;
    }

    @PreDestroy
    public String logout() {

        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        HttpSession session = request.getSession(true);
        session.invalidate();
        logger.info(new Date() + " : " + user.getUsername() + " logged out.");
        user = null;

        return "index.xhtml?faces-redirect=true";
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}
